#include "music.hpp"
#include "music_if.hpp"
#include "simpleStack.hpp"
#include "i2c.h"
#include <algorithm>

void MusicCtl::resize() 
{
    capacity_ += 5;
    auto *new_musics = new music_t[capacity_];
    std::copy(musics_, musics_ + size_, new_musics);
    delete[] musics_;
    musics_ = new_musics;
}

void MusicCtl::loadSettings()
{
    beep->setVolume(70);
    phone->setVolume(0);

    extern lv_obj_t *localMusicLabel;
    lv_label_set_text_fmt(localMusicLabel, "本地音乐 (%d)", size_);

    // TODO: 从 rom 中加载上次的播放状态
}

void MusicCtl::addMusic(const music_t &music)
{
    if (size_ >= capacity_) {
        resize();
    }
    musics_[size_++] = music;
}

void MusicCtl::setPlayProcess(int16_t process)
{
    playProcess = process;

    if (playProcess > musics_[playingMusicIndex].duration) {
        playNext();
    } else {
        playProcess = playProcess <= 0 ? 0 : playProcess;
        adjustTim(playProcess);
        music_ui->setPlayProcess();
    }
}

void MusicCtl::playNext(int8_t flag)
{
    music_ui->resetUi();
    SimpleStack::getInst()->push(playingMusicIndex);
    if (flag == 0) {
        playingMusicIndex = isRandom ? getRand() : (playingMusicIndex + 1) % size_;
    } else {
        playingMusicIndex = (playingMusicIndex + flag + size_) % size_;  // 加上 size_ 是为了防止负数
    }
    playProcess = 0;
    startPlayMusic();
    music_ui->setUI();
}

void MusicCtl::playPrev() 
{
    auto index = SimpleStack::getInst()->pop();
    if (index == uint16_t(-1)) {
        return;
    }

    music_ui->resetUi();
    playingMusicIndex = index;
    playProcess = 0;
    startPlayMusic();
    music_ui->setUI();
}

void MusicCtl::playOtherMusic(uint16_t index) 
{
    if (index == playingMusicIndex) {
        return;
    }

    music_ui->resetUi();
    SimpleStack::getInst()->push(playingMusicIndex);
    playingMusicIndex = index;
    playProcess = 0;
    startPlayMusic();
    music_ui->setUI();
}
